import torch
import numpy as np
#1.Numpy数组转化为tensor向量
print('1.numpy数组转化为tensor向量')
numpy_array=np.array([[1,2,3],[4,5,6]])
print('numpy数组如下\n',numpy_array)

tensor_from_numpy=torch.from_numpy(numpy_array)
print('转换后的张量\n',tensor_from_numpy)

numpy_array[0,0]=100
print('修改后的numpy数组\n',numpy_array)
print('tensor张量也会同步变化\n',tensor_from_numpy)

#2.pytorch张量转换为Numpy数组
print('\n2.pytorch张量转化为numpy数组')
tensor=torch.tensor([[7,8,9],[10,11,12]],dtype=torch.float32)
print('pytorch张量：\n',tensor)
numpy_from_tensor=tensor.numpy()
print('转换后的numpy数组：\n',numpy_from_tensor)

#修改张量，观察numpy数组变化
tensor[0,0]=77
print('修改后的pytorch张量：\n',tensor)
print('Numpy数组也会同步变化',numpy_from_tensor)
numpy_from_tensor[0,0]=88
print('修改后的numpy的数组：\n',tensor)
print('tensor张量是否变化',numpy_from_tensor)

#3.不共享的内存的情况下（需要复制数据）
print('\n3.使用clone()保证独立数据')
tensor_independent=torch.tensor([[13,14,15],[16,17,18]],dtype=torch.float32)
numpy_independent=tensor_independent.clone().numpy()#使用clone复制数据
print('原始张量:\n',tensor_independent)
tensor_independent[0,0]=0#修改张量数据
print('修改后tensor张量：\n',tensor_independent)
print('Numpy数组：\n',numpy_independent)